package com.hj.security.ui;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hj.security.R;
import com.hj.security.domain.UpdateInfo;
import com.hj.security.engine.DownloadTask;
import com.hj.security.engine.UpdateInfoService;

public class SplashActivity extends Activity {

	private static final String TAG = "SplashAction";
	public static final int UPDATE_ERROR = 1;
	public static final int INSTALL = 0;
	private TextView tv_version;
	private LinearLayout ll;
	private String version;
	private ProgressDialog progressDialog;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(isNeedUpdate(version)){
					System.out.println("弹出");
					showUpdateDialog();
				}				
				break;
			case UPDATE_ERROR:
				Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
			
		}
	};
	private UpdateInfo updateInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 不要标题栏
		//注意： 隐去标题（应用的名字) 此设定必须要写在setContentView之前，否则会有异常!
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash);
		// 设置全屏显示（隐去电池等图标和一切修饰部分（状态栏部分））
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		tv_version = (TextView) findViewById(R.id.tv_splash_version);
		version = getVersion();
		tv_version.setText("版本号:" + version);

		ll = (LinearLayout) findViewById(R.id.ll_splash_main);
		AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
		alphaAnimation.setDuration(3000);
		ll.setAnimation(alphaAnimation);
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMessage("正在下载");
		
		new Thread(){
			public void run() {
				try {
					UpdateInfoService updateInfoService = new UpdateInfoService(SplashActivity.this);
					updateInfo = updateInfoService.getUpdateInfo(R.string.serverUrl);
					Log.i("SplashAction", updateInfo.getVersion());
					Log.i("SplashAction", updateInfo.getDescription());
					Log.i("SplashAction", updateInfo.getApkurl());
					
					sleep(1000);
					handler.sendEmptyMessage(0);
				} catch (Exception e) {
					loadMainUI();
					//e.printStackTrace();
					//throw new RuntimeException("无法连接到服务器");
					System.out.println("无法连接到服务器");
				}
			};
		}.start();
		
	}

	private void showUpdateDialog(){
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("升级提醒");
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setMessage(updateInfo.getDescription());
		builder.setCancelable(true);
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					File dir = new File(Environment.getExternalStorageDirectory(),"/security/update");
					if(!dir.exists()){
						dir.mkdirs();
					}
				String filePath = Environment.getExternalStorageDirectory()+"/security/update/"+getString(R.string.apkName);
				UpdateTask updateTask = new UpdateTask(updateInfo.getApkurl(), filePath);
				progressDialog.show();
				new Thread(updateTask).start();
				}else{
					Toast.makeText(SplashActivity.this, "SD卡不可用，请插入SD卡", Toast.LENGTH_LONG).show();
					loadMainUI();
				}
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				loadMainUI();
			}
		});
		builder.create().show();
	}

	private boolean isNeedUpdate(String version) {
		if(updateInfo==null){
			Log.i("SplashAction", "updateInfo为空");
			Toast.makeText(this, "获取更新信息失败", Toast.LENGTH_LONG).show();
			return false;
		}
		String newVersion = updateInfo.getVersion();
		if (newVersion.equals(version)) {
			System.out.println("不用更新");
			loadMainUI();
			return false;
		} else {
			System.out.println("要更新");
			Log.i(TAG, "当前版本"+version);
			Log.i(TAG, "最新版本"+newVersion);
			return true;
		}
	}

	private String getVersion() {
		try {
			PackageManager pm = getPackageManager();
			PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "版本号未知";
		}

	}
	/**
	 * 打开主页面
	 */
	private void loadMainUI(){
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		this.finish();
	}
	/**
	 * 安装apk 
	 * @param file 要安装的apk的目录 
	 */
	private void install(File file){
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		this.finish();
		startActivity(intent);
	}
	
	class UpdateTask implements Runnable{
		private String path;
		private String filePath;
		
		public UpdateTask(String path, String filePath) {
			super();
			this.path = path;
			this.filePath = filePath;
		}

		@Override
		public void run() {
			try {
				File file = DownloadTask.getFile(path, filePath, progressDialog);
				progressDialog.dismiss();
				if(file==null){
					System.out.println("file为空");
				}
				install(file);
				//Message msg = new Message();
				//msg.what=INSTALL;
				//handler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
				progressDialog.dismiss();
				Message msg = new Message();
				msg.what=UPDATE_ERROR;
				msg.obj="更新失败";
				handler.sendMessage(msg);
				System.out.println("更新失败");
				loadMainUI();
			}
			
		}
		
	}
}
